package com.lineage.server.datatables;

import com.lineage.DatabaseFactory;
import com.lineage.server.model.Instance.L1ItemInstance;
import com.lineage.server.utils.PerformanceTimer;
import com.lineage.server.utils.SQLUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class ItemLimitTable {
  private static final Log _log = LogFactory.getLog(ItemLimitTable.class);
  
  private static ItemLimitTable _instance;
  
  public static final Map<Integer, Integer> TIME = new HashMap<>();
  
  public static ItemLimitTable get() {
    if (_instance == null)
      _instance = new ItemLimitTable(); 
    return _instance;
  }
  
  public void load() {
    PerformanceTimer timer = new PerformanceTimer();
    Connection con = null;
    PreparedStatement pstm = null;
    ResultSet rs = null;
    try {
      con = DatabaseFactory.get().getConnection();
      pstm = con.prepareStatement("SELECT * FROM `w_物品掉落限制一`");
      rs = pstm.executeQuery();
      while (rs.next()) {
        int key = rs.getInt("itemid");
        int value = rs.getInt("count");
        TIME.put(Integer.valueOf(key), Integer.valueOf(value));
      } 
    } catch (SQLException e) {
      _log.error(e.getLocalizedMessage(), e);
    } finally {
      SQLUtil.close(rs);
      SQLUtil.close(pstm);
      SQLUtil.close(con);
    } 
    _log.info("载入掉落数量限制道具: " + TIME.size() + "(" + timer.get() + "ms)");
  }
  
  public void update(L1ItemInstance item) throws Exception {
    Connection con = null;
    PreparedStatement pstm = null;
    try {
      con = DatabaseFactory.get().getConnection();
      pstm = con.prepareStatement("UPDATE `w_物品掉落限制一` SET `count`=`count` - 1 WHERE `itemid`= ?");
      pstm.setInt(1, item.getItemId());
      pstm.execute();
    } catch (SQLException e) {
      _log.error(e.getLocalizedMessage(), e);
    } finally {
      SQLUtil.close(pstm);
      SQLUtil.close(con);
    } 
  }
  
  public void update2(int item, int i) throws Exception {
    Connection con = null;
    PreparedStatement pstm = null;
    try {
      con = DatabaseFactory.get().getConnection();
      pstm = con.prepareStatement("UPDATE `w_物品掉落限制一` SET `count`= ? WHERE `itemid`= ?");
      pstm.setInt(1, i);
      pstm.setInt(2, item);
      pstm.execute();
    } catch (SQLException e) {
      _log.error(e.getLocalizedMessage(), e);
    } finally {
      SQLUtil.close(pstm);
      SQLUtil.close(con);
    } 
  }
}
